import Vue from "vue";
import axios from "axios";
// Vue.use(axios);
const qs = require('qs');

import VueCookies from 'vue-cookies'
Vue.use(VueCookies)

import {
    Toast
} from 'vant';
Vue.use(Toast);  


//$cookies.set('token','4c208dc8-421f-430f-af91-2f846b093c57');//lc陈绍


axios.defaults.baseURL = process.env.BASE_URL;
// axios.defaults.baseURL = '/api';
axios.defaults.timeout = 30000;
//设置默认请求头
axios.defaults.headers.post['Content-Type'] = 'application/json; charset=utf-8';
// axios.defaults.headers = {
//     "Content-Type": "application/x-www-form-urlencoded",
// }
var toast;
axios.interceptors.request.use(request => {
    // Toast.allowMultiple();
    // toast=Toast.loading({
    //     mask: true,
    //     message: '加载中...',
    //     duration: 0, // 持续展示 toast
    //     forbidClick: true
    // });
    if (request.data && request.headers['Content-Type'] === 'application/x-www-form-urlencoded') {
        request.data = qs.stringify(request.data); 
    }
    request.headers["MG-SK"] = 'df71cb036';
    
    let  expired=$cookies.get('expired');
    let  manager_id=$cookies.get('manager_id');
    let currentTime=new Date().getTime();
    var token = $cookies.get('token') || localStorage.getItem('token');
    //判断是否需要刷新token
    if( $cookies.get('getTokenFlag')!=1&&expired&&expired>currentTime&&expired-currentTime<10*60*1000){
        getToken(token,manager_id);
    };
    if (token && token != null) {
        // request.headers["Authorization"] = 'Bearer ' + token;
         request.headers["AUTH-TOKEN"] = token;
    } else {
        //统一设置。全部页面需要token 
        var returnUrl = window.location.href;
        //当不是登陆页时
        if(window.location.pathname!='/'){
            window.location.href = window.location.protocol+"//" + window.location.host + "?returnUrl=" + returnUrl;
        };
    }

    return request
}, error => {
    return Promise.reject(error);
})

axios.interceptors.response.use(response => {
    // toast.clear();
    //token过期
    // console.log(response);/
    if (response.data.code == 401) {
        $cookies.remove('token');
        var returnUrl = window.location.href;
        window.location.href = window.location.protocol+"//" + window.location.host + "?returnUrl=" + returnUrl;
    };
    return response.data;
}, error => {
    if (response.data.code == 401) {
        $cookies.remove('token');
        var returnUrl = window.location.href;
        window.location.href = window.location.protocol+"//" + window.location.host + "?returnUrl=" + returnUrl;
    };
    // toast.clear();
    if (error.response) {
        Toast.fail(error);
    }
    return Promise.reject(error);
})

//当离token过期还有10分钟的时候自动刷新token
function getToken(old_token,manager_id){
    $cookies.set('getTokenFlag',1);
    axios.post(process.env.BASE_URL+'/manage/api/auth/refresh/token', JSON.stringify({
        handshake:"",
        data:{
            old_token: old_token,
            manager_id: manager_id
        },
      }))
      .then(function (response) {
        $cookies.set('getTokenFlag',0);
        if(response.code==200){
            let expired=new Date(response.data.expired_at).getTime();
            $cookies.set('expired',expired);
            $cookies.set('token',response.data.token);
        };
      })
      .catch(function (error) {
        $cookies.set('getTokenFlag',0);
        console.log(error);
      })
}




export default axios;